import { JwtVerifyService } from '@app/jwt-verify';
import { CanActivate, ExecutionContext, Inject, Injectable } from '@nestjs/common';
import { DbService } from '../../db/db.service';
import { ConfigureService } from '@app/configure';
import { ReqAttrs } from '../../constant';

@Injectable()
export class AuthGuard implements CanActivate {
	@Inject()
	private readonly config:ConfigureService
	@Inject()
	private readonly jwt:JwtVerifyService
	@Inject()
	private readonly db:DbService

	async canActivate(
		context: ExecutionContext,
	): Promise<boolean> {
		let request = context.switchToHttp().getRequest()

		const route = request.route
		let path:string = route.path

		const white = this.config.get('white')
		const routePrefix = this.config.get('apiPrefix')
		if(routePrefix != undefined && routePrefix.length > 0) {
			path = path.substring(routePrefix.length + 1)
		}

		const token = request.headers.authorization
		if(!white.includes(path) && !token) return false

		if(token) {
			const jwtConfig = this.config.get('jwt')
			const payload = this.jwt.verify(token, {secret : jwtConfig.secret})
			if(!payload) return false

			const memberId = (payload.key - jwtConfig.scale) / jwtConfig.scale

			const member = await this.db.member.findOne({id : memberId}, ['enable', 'roles', 'canSuper', 'belong', 'merchantId'])
			if(!member || member.enable == false) return false
			if(member.canSuper == false) {

			}else {}


			member.id = memberId

			request[ReqAttrs.BELONG] = member.belong
			request[ReqAttrs.MEMBER_ID] = memberId
			request[ReqAttrs.IS_SUPER] = member.canSuper
			request[ReqAttrs.MERCHANT_ID] = member.merchantId
		}


		request.locale = request.headers.locale

		return true;
	}
}
